var scripts = [null, "../assets/js/jquery.validate.js", 
               "../assets/js/date-time/bootstrap-datepicker.js",
               "../assets/js/date-time/bootstrap-timepicker.js",
               "../assets/js/jquery.validate_msgzh.js", null]
$('.page-content-area').ace_ajax('loadScripts', scripts, function () {
  jQuery(function ($) {
	getOrderById()
	renderExpressCompanyAll();
	
	$('.date-picker').datepicker({
	      language: 'ch',
	      autoclose: true,
	      todayHighlight: true
	    }).next().on(ace.click_event, function () {
	      $(this).prev().focus();
	    })
	    
	$('#expressTime').timepicker({
		minuteStep: 1,
		showSeconds: true,
		showMeridian: false,
		disableFocus: true,
		icons: {
			up: 'fa fa-chevron-up',
			down: 'fa fa-chevron-down'
		}
	}).on('focus', function() {
		$('#expressTime').timepicker('showWidget');
	}).next().on(ace.click_event, function(){
		$(this).prev().focus();
	});
	
	$('#deliveryTime2').timepicker({
		minuteStep: 1,
		showSeconds: true,
		showMeridian: false,
		disableFocus: true,
		icons: {
			up: 'fa fa-chevron-up',
			down: 'fa fa-chevron-down'
		}
	}).on('focus', function() {
		$('#deliveryTime2').timepicker('showWidget');
	}).next().on(ace.click_event, function(){
		$(this).prev().focus();
	});

    function getOrderById() {
      var url = $utils.ajax.setUrl("store/order/getOrderById");
      var params = {}
      params.orderId = $utils.string.getQueryParam("id")
      return axios.post(url, params)
        .then(function (response) {
          renderOrder(response.body)
        })
        .catch(function (error) {
        });
    }

    function renderOrder(body) {
    	var order = body.order;
    	var itemList = body.itemList;
    	var post = body.post;
    	var express = body.express;
    	var expressDetailList = body.expressDetailList;
    	$("#orderId").val(order.ORDER_ID);
    	$("#orderNo").val(order.ORDER_NO);
    	$("#goodsCode").val(order.GOODS_CODE);
    	$("#goodsName").val(order.GOODS_NAME);
    	$("#goodsDetail").val(order.GOODS_DETAIL);
    	$("#goodsNum").val(order.GOODS_NUM);
    	$("#orderIntegral").val(order.ORDER_INTEGRAL);
    	$("#buserMobile").val(order.BUSER_MOBILE);
    	$("#orderStatus").val(order.ORDER_STATUS);
    	
    	$("#postId").val(post.POST_ID);
    	$("#postName").val(post.POST_NAME);
    	$("#postPhone").val(post.POST_PHONE);
    	$("#postAddress").val(post.POST_ADDRESS);
    	$("#postAreaCode").val(post.POST_AREA_CODE);
    	
    	$("#expressId").val(express.EXPRESS_ID);
    	$("#companyId").val(express.COMPANY_ID);
    	$("#expressNo").val(express.EXPRESS_NO);
    	$("#planArrivalDate").val(express.PLAN_ARRIVAL_DATE);
    	$("#deliveryAddress").val(express.DELIVERY_ADDRESS);
    	var DELIVERY_TIME = express.DELIVERY_TIME;
    	$("#deliveryTime1").val(DELIVERY_TIME.substr(0,10));
    	$("#deliveryTime2").val(DELIVERY_TIME.substr(11));
    	renderOrderExpress();
    }
    
    $("#updateOrderStatus").click(function () {
    	updateOrderStatus();
    })
    function updateOrderStatus() {
        var params = {}
        params.orderId = $("#orderId").val();
        params.orderStatus = $("#orderStatus").val();

        var url = $utils.ajax.setUrl("store/order/updateOrderStatus");
        axios.post(url, params)
          .then(function (response) {
            bootbox.alert(response.msg);
          })
      }
    
    $("#updateOrderPost").click(function () {
    	updateOrderPost();
    })
    function updateOrderPost() {
        var params = {}
        params.postId = $("#postId").val();
        params.postName = $("#postName").val();
        params.postPhone = $("#postPhone").val();
        params.postAddress = $("#postAddress").val();
        params.postAreaCode = $("#postAreaCode").val();
        
        if ($utils.string.isNull(params.postId)) {
            bootbox.alert("请求错误，请刷新后重试。")
            return false
        }
        
        if ($utils.string.isNull(params.postName)) {
            bootbox.alert("邮寄信息收件人姓名不能为空。")
            return false
        }
        if ($utils.string.isNull(params.postPhone)) {
        	bootbox.alert("邮寄信息收件人电话不能为空。")
            return false
        }
        if ($utils.string.isNull(params.postAddress)) {
        	bootbox.alert("邮寄信息收件人地址不能为空。")
            return false
        }
        
        if (params.postName.length>100) {
            bootbox.alert("邮寄信息收件人姓名不能超过100字")
            return false
        }
        if (params.postPhone.length>20) {
            bootbox.alert("邮寄信息收件人电话不能超过20字")
            return false
        }
        if (params.postAddress.length>200) {
            bootbox.alert("邮寄信息收件人地址不能超过200字")
            return false
        }
        
        var url = $utils.ajax.setUrl("store/order/updateOrderPost");
        axios.post(url, params)
          .then(function (response) {
            bootbox.alert(response.msg);
          })
      }
    
    $("#updateOrderExpress").click(function () {
    	updateOrderExpress();
    })
    function updateOrderExpress() {
        var params = {}
        params.expressId = $("#expressId").val();
        params.companyId = $("#companyId").val();
        params.expressNo = $("#expressNo").val();
        params.planArrivalDate = $("#planArrivalDate").val();
        params.deliveryAddress = $("#deliveryAddress").val();
        var deliveryTime1 = $("#deliveryTime1").val();
    	var deliveryTime2 = $("#deliveryTime2").val();
    	params.deliveryTime= deliveryTime1+' '+deliveryTime2;

        if ($utils.string.isNull(params.expressId)) {
            bootbox.alert("请求错误，请刷新后重试。")
            return false
        }
        if ($utils.string.isNull(params.companyId)) {
            bootbox.alert("快递公司不能为空。")
            return false
        }
        if ($utils.string.isNull(params.expressNo)) {
            bootbox.alert("快递编号不能为空。")
            return false
        }
        if ($utils.string.isNull(params.planArrivalDate)) {
        	bootbox.alert("预计到达日期不能为空。")
            return false
        }
        
        if (params.expressNo.length>36) {
            bootbox.alert("快递编号不能超过36字")
            return false
        }
        
        if (params.planArrivalDate.length != 10) {
            bootbox.alert("预计到达日期格式不正确。请输入格式正确的日期\n\r日期格式：yyyy-mm-dd\n\r例    如：2008-08-08\n\r")
            return false
        }
        
        if (params.planArrivalDate.indexOf("0") == 0) {
            bootbox.alert("预计到达日期年份不正确。")
            return false
        }
        
        if ($utils.string.isNull(params.planArrivalDate)) {
        	bootbox.alert("发货地址不能为空。")
            return false
        }
        
        if (params.planArrivalDate.length>300) {
            bootbox.alert("发货地址不能超过300字")
            return false
        }
        
        if ($utils.string.isNull(deliveryTime1)) {
        	bootbox.alert("发货日期不能为空。")
            return false
        }
    	
    	if (deliveryTime1.length != 10) {
            bootbox.alert("发货日期格式不正确。请输入格式正确的日期\n\r日期格式：yyyy-mm-dd\n\r例    如：2008-08-08\n\r")
            return false
        }
        
        if (deliveryTime2.length != 8) {
            bootbox.alert("发货时间格式不正确。请输入格式正确的时间\n\r时间格式：hh-mi-ss\n\r例    如：10:10:10\n\r")
            return false
        }
        
        var url = $utils.ajax.setUrl("store/order/updateOrderExpress");
        axios.post(url, params)
          .then(function (response) {
            bootbox.alert(response.msg);
          })
      }
    
    /*快递公司列表*/
    function renderExpressCompanyAll() {
    	var url = $utils.ajax.setUrl("store/order/getExpressCompanyAll");
    	axios.post(url, {})
    		.then(function (response) {
    		var companyList = response.body;
    		var html = ''
    		$.each(companyList, function (key, val) {
    		    html += '<option value="' + val.COMPANY_ID + '">' + val.EXPRESS_COMPANY + '</option>'
    		});
    		$("#companyId").html(html);
    	});
    }
    
    function renderOrderExpress() {
    	var grid_expressDetail = "#grid-table-expressDetail";
        var pager_expressDetail = "#grid-pager-expressDetail";
        var url = $utils.ajax.setUrl("store/order/getOrderExpressDetailList")
        var params={}
        params.expressId = $("#expressId").val();
        $(window).on('resize.jqGrid', function () {
          $(grid_expressDetail).jqGrid( 'setGridWidth', $(grid_expressDetail).parents(".tab-content").width()-15);
        })
        var parent_column = $(grid_expressDetail).closest('[class*="col-"]');
        $(document).on('settings.ace.jqGrid' , function(ev, event_name, collapsed) {
          if( event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed' ) {
            setTimeout(function() {
              $(grid_expressDetail).jqGrid( 'setGridWidth', parent_column.width() );
            }, 0);
          }
        })
        var optinons=jqSetting(grid_expressDetail,pager_expressDetail,url);
        optinons.url=url;
        optinons.postData=params
        optinons.caption=false
        optinons.colNames=['ID','快递时间', '快递星期','快递描述','操作'];
        optinons.colModel=[
          {display:"DETAIL_ID",name:'DETAIL_ID',index:'DETAIL_ID', width:60, sorttype:"int", hidden:true,editable: true},
          {display:"快递时间",name:'EXPRESS_TIME',index:'EXPRESS_TIME',width:200, editable:true, sorttype:"date",hidden:false},
          {display:"快递星期",name:'EXPRESS_WEEK',index:'EXPRESS_WEEK',width:400, editable:true, sorttype:"date",hidden:false},
          {display:"快递描述",name:'EXPRESS_REMARK',index:'EXPRESS_REMARK',width:400, editable:true, hidden:false},
          {display:"操作",name:'oper',index:'oper', width:150,editable: true,formatter:operation},
        ];
        jQuery(grid_expressDetail).jqGrid(optinons);
        function operation(v,o,r) {
            var html=""
            html+='<span onclick="delDetail('+r.DETAIL_ID+')" class="ace-icon fa fa-trash-o red bigger-150 cursor-p tt-cursor"></span>'
            return html
        }
        /*jqGrid 初始化*/
        jQuery(grid_selector).jqGrid(options);
        //初始化表格宽度
        var parent_column = $(grid_selector).parents('.tab-content').width() - 15;
        initGridWidth(grid_selector, parent_column);
      }
    
    $("#addOrderExpress").click(function (e) {
    	addOrderExpress();
    })
    
    /**
     * 新增除快递配送详情
     */
    function addOrderExpress() {
    	var url=$utils.ajax.setUrl("store/order/addOrderExpressDetail");
    	var params={}
    	params.expressId = $("#expressId").val();
    	var expressDate = $("#expressDate").val();
    	var expressTime = $("#expressTime").val();
    	params.expressTime= expressDate+' '+expressTime;
    	params.expressRemark=$("#expressRemark").val();
    	
    	if ($utils.string.isNull(params.expressId)) {
        	bootbox.alert("快递信息ID不能为空。")
            return false
        }
    	
    	if ($utils.string.isNull(expressDate)) {
        	bootbox.alert("配送日期不能为空。")
            return false
        }
    	
    	if (expressDate.length != 10) {
            bootbox.alert("配送日期格式不正确。请输入格式正确的日期\n\r日期格式：yyyy-mm-dd\n\r例    如：2008-08-08\n\r")
            return false
        }
        
        if (expressTime.length != 8) {
            bootbox.alert("配送时间格式不正确。请输入格式正确的时间\n\r时间格式：hh-mi-ss\n\r例    如：10:10:10\n\r")
            return false
        }
        debugger
        var arys1 = new Array();
        arys1 = expressDate.split('-');     //日期为输入日期，格式为 2013-3-10
        var ssdate = new Date(arys1[0], parseInt(arys1[1] - 1), arys1[2]);
        var  week1=String(ssdate.getDay()).replace("0","日").replace("1","一").replace("2","二").replace("3","三").replace("4","四").replace("5","五").replace("6","六")//就是你要的星期几
        var week="周"+week1;
        params.expressWeek = week;
    	axios.post(url, params)
            .then(function (response) {
            	$('#grid-table-expressDetail').trigger("reloadGrid");
            }).catch(function (error) {
        });
    }
    
  });
});


/**
 * 删除快递配送详情
 * @param id
 */
function delDetail(id) {
  	bootbox.confirm("确定删除吗",function (result) {
  	if(result){
  		var url=$utils.ajax.setUrl("store/order/deleteOrderExpressDetailById");
  		var params={}
  		params.detailId =id;
  		axios.post(url, params)
  			.then(function (response) {
  				$('#grid-table-expressDetail').trigger("reloadGrid");
  			})
  			.catch(function (error) {
  	        });
  	    }
  	  });
  }

